<template>
  <div class="users-contain">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="15">
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisibleAdd = true"
            >添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              :value="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="180">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showdialogEdit(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showdialogRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="+total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisibleAdd" top="20vh">
      <el-form
        :model="formAddUser"
        label-width="10%"
        :rules="rulesForm"
        ref="ruleFormAdd"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formAddUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="10%">
          <el-input v-model="formAddUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="10%">
          <el-input v-model="formAddUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" label-width="10%">
          <el-input v-model="formAddUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogVisibleEdit"
      @close="resetForm"
    >
      <el-form :model="formEditUser" :rules="rulesForm" ref="ruleFormEdit">
        <el-form-item label="用户名" prop="username" label-width="10%">
          <el-input v-model="formEditUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="10%">
          <el-input v-model="formEditUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" label-width="10%">
          <el-input v-model="formEditUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配用户的角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="dialogVisibleRoles"
      @close="setRoleDialogClosed"
    >
      <el-form :model="rolesData" ref="ruleFormEdit">
        <p>当前的用户: {{ rolesData.username }}</p>
        <p>当前的角色: {{ rolesData.role_name }}</p>
        <el-form-item label="分配新角色">
          <el-select placeholder="请选择" v-model="selectedRoleId">
            <el-option
              v-for="item in roleList"
              :label="item.roleName"
              :key="item.id"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleRoles = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // 自定义邮箱和手机的验证规则
    var validateEmail = (rule, value, callback) => {
      const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!emailReg.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      }
      callback()
    }
    const validateMobile = (rule, value, callback) => {
      const mobileReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (!mobileReg.test(value)) {
        callback(new Error('手机号格式不正确'))
      }
      callback()
    }
    return {
      // 获取查取请求参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表数据
      userList: [],
      // 总条目数
      total: '',
      // 添加用户对话框是否显示
      dialogVisibleAdd: false,
      // 编辑用户对话框是否显示
      dialogVisibleEdit: false,
      formAddUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则
      rulesForm: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: validateEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: validateMobile,
            trigger: 'blur'
          }
        ]
      },
      // 编辑用户的请求参数
      formEditUser: {
        username: '',
        id: '',
        email: '',
        mobile: ''
      },
      // 分配角色对话框是否显示
      dialogVisibleRoles: false,
      // 分配角色的数据
      rolesData: {},
      // 保存所有的角色信息
      roleList: [],
      // 分配角色的id
      selectedRoleId: ''
    }
  },
  methods: {
    // 获取用户数据列表
    async getUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取管理员列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改用户状态
    async userStateChanged(row) {
      console.log(row)
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('设置状态失败')
      }
      row.mg_state = !row.mg_state
      this.$message.success('更新状态成功')
    },
    // pagesize改变时触发
    handleSizeChange(val) {
      // console.log(val)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 当前页码发生改变是触发
    handleCurrentChange(val) {
      // console.log(val)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 添加用户并显示对话框
    addUser() {
      this.$refs.ruleFormAdd.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        const { data: res } = await this.$http.post('/users', this.formAddUser)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户已存在')
        }
        this.$message.success('添加用户成功')
        this.dialogVisibleAdd = false
        this.getUserList()
        // 重置表单
        this.$refs.ruleFormAdd.resetFields()
      })
    },
    // 显示编辑用户对话框
    async showdialogEdit(id) {
      // console.log(id)
      this.dialogVisibleEdit = true
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.formEditUser = res.data
    },
    // 编辑用户对话框提交
    editUser() {
      this.$refs.ruleFormEdit.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('填写的信息有误')
        const { id, email, mobile } = this.formEditUser
        const { data: res } = await this.$http.put('users/' + id, {
          email,
          mobile
        })
        console.log(res)
        this.$message.success('修改用户成功')
        this.dialogVisibleEdit = false
        this.getUserList()
      })
    },
    //  表单的重置
    resetForm() {
      this.$refs.ruleFormEdit.resetFields()
    },
    // 删除用户信息
    deleteUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const { data: res } = await this.$http.delete('users/' + id)
          console.log(res)
          if (res.meta.status === 400) {
            return this.$message.error(res.meta.msg)
          }
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取角色的信息和显示分配角色的对话框
    async showdialogRoles(row) {
      this.dialogVisibleRoles = true
      console.log(row)
      this.rolesData = row
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 保存修改后的角色信息
    async saveRole() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择需要分配的角色')
      }
      // console.log(this.roleId)
      const { data: res } = await this.$http.put(
        `users/${this.rolesData.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      console.log(res)
      this.dialogVisibleRoles = false
      this.getUserList()
    },
    setRoleDialogClosed() {
      // 当关闭对话框的时候，重置下拉框中的内容
      this.selectedRoleId = ''
      // this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped></style>
